package com.scalar.chiptrack.operations.reports.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.operations.reports.forms.TransitForm;
import com.scalar.chiptrack.operations.reports.dao.DataDumpReportsDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.users.User;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Sudhakar.
 * Date: Dec 30, 2003
 * Time: 8:31:51 PM
 */
public class lotsIntransitAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/lotsIntransit.do";

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response )
            throws Exception
    {
        HttpSession session = request.getSession();
        User user = ( User ) session.getAttribute( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
            return ( mapping.findForward( "login" ) );
        }

        TransitForm transitForm = (TransitForm)form;

        String action = request.getParameter( "action" );
        if ( action == null )
            action = "";

        request.setAttribute( "action", action );
        HashMap<String, String> errors = new HashMap<String, String>();
        HashMap<String, String> info = new HashMap<String, String>();
        ArrayList lotInfoList = null;
        Workbook workbook = null;
        String fileName = "";

        if ( action.equals( "" ) )
        {
           request.setAttribute("processTypeList", NewProductDAO.loadAllProcessesFromDB(null, true));
           request.setAttribute("vendorList", VendorDAO.getVendorNamesByPsType(null, "ALL") );

           request.setAttribute( "shippedLotsList", ShippedLotDAO.loadAllTransitLots("0", "0") );

           return ( mapping.findForward( "success" ) );
        }
        if (action.equalsIgnoreCase( "search" ))
        {
            ArrayList transitList = ShippedLotDAO.loadAllTransitLots(transitForm.getProcessType(), transitForm.getVendorName() );
            request.setAttribute("processTypeList", NewProductDAO.loadAllProcessesFromDB(null, true));
            request.setAttribute("vendorList", VendorDAO.getVendorNamesByPsType(null, "ALL") );
            if(transitList != null && transitList.size() > 0 )
            {
                request.setAttribute("shippedLotsList", transitList);
                return ( mapping.findForward( "success" ) );
            }
            else
            {
                if (!"0".equalsIgnoreCase(transitForm.getProcessType() ) && !"0".equalsIgnoreCase(transitForm.getVendorName() ) )
                {
                    info.put( "<font color='Blue'> " + transitForm.getProcessType().toUpperCase() + "</font> Delayed Transit Lots are not found for <font color='Blue'>" + transitForm.getVendorName().toUpperCase() +"</font> ", null );
                }
                else if (!"0".equalsIgnoreCase(transitForm.getProcessType() ) && "0".equalsIgnoreCase(transitForm.getVendorName() ) )
                {
                    info.put( "<font color='Blue'> " + transitForm.getProcessType().toUpperCase() + "</font> Delayed Transit Lots are not found ", null );
                }
                else if ("0".equalsIgnoreCase(transitForm.getProcessType() ) && !"0".equalsIgnoreCase(transitForm.getVendorName() ) )
                {
                    info.put( "Delayed Transit Lots are not found for <font color='Blue'>" + transitForm.getVendorName().toUpperCase() +"</font> ", null );
                }
                else
                {
                    info.put( "Delayed Transit Lots are not found for this Search ", null );
                }
                request.setAttribute("shippedLotsList", new ArrayList());
                request.setAttribute( SessionKeys.INFO_MESSAGES, info );
                return ( mapping.findForward( "success" ) );
            }
        }
        if ( action.equals( "save" ) )
        {
            String shippingLotID[] = request.getParameterValues( "transitId" );
            try
            {
                ShippedLotDAO.closeTransitLots( null, shippingLotID, user.getUserName() );

                info.put( "Selected Lots are Closed Successfully ", null );
                request.setAttribute( SessionKeys.INFO_MESSAGES, info );
            }
            catch ( ScalarException se )
            {
                se.getRootCause().printStackTrace();
                errors.put( "Internal Server Error:", "Could not Close the Transit Lots " );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            }
            request.setAttribute( "shippedLotsList", ShippedLotDAO.loadAllTransitLots( transitForm.getProcessType(), transitForm.getVendorName()) );
            request.setAttribute("processTypeList", NewProductDAO.loadAllProcessesFromDB(null, true));
            request.setAttribute("vendorList", VendorDAO.getVendorNamesByPsType(null, "ALL") );
            return ( mapping.findForward( "success" ) );
        }

        if ( action.equalsIgnoreCase ( "transitInfo" ) )
        {               
            if ( transitForm.getProcessName() == null || "0".equalsIgnoreCase(transitForm.getProcessName()))
            {
                  request.setAttribute( "partNumberList", new ArrayList() );
                  request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, "ALL") );
            }
            else
            {
                if ( transitForm.getBaseProductId() > 0 )
                {

                    request.setAttribute( "partNumberList", ProductDao.getPartNumberByBaseProductAndPsTypeList(transitForm.getProcessName() , transitForm.getBaseProductId() ) );
                }
                else
                {
                    request.setAttribute( "partNumberList", ProductDao.loadAllPartsForProcessTypeByPsType( transitForm.getProcessName() ) );
                }
                request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, transitForm.getProcessName() ));
            }

            request.setAttribute( "processTypeList", NewProductDAO.loadAllProcessesFromDB( null, true ) );
            request.setAttribute( "baseProductList", ProductDao.loadChipBaseProducts(null) );

            return( mapping.findForward( "shipmentReport" ) );
        }

        if ( action.equalsIgnoreCase ( "receiveLotInfo" ) )
        {

            if ( transitForm.getProcessName() == null || "0".equalsIgnoreCase(transitForm.getProcessName()))
            {
                  request.setAttribute( "partNumberList", new ArrayList() );
                  request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, "ALL") );
            }
            else
            {
                if ( transitForm.getBaseProductId() > 0 )
                {

                    request.setAttribute( "partNumberList", ProductDao.getPartNumberByBaseProductAndPsTypeList(transitForm.getProcessName() , transitForm.getBaseProductId() ) );
                }
                else
                {
                    request.setAttribute( "partNumberList", ProductDao.loadAllPartsForProcessTypeByPsType( transitForm.getProcessName() ) );
                }
                request.setAttribute( "locationList",    VendorDAO.getVendorNamesByPsType(null, transitForm.getProcessName() ));
            }

            request.setAttribute( "processTypeList",  loadReceiveLotProcess() );
            request.setAttribute( "baseProductList", ProductDao.loadChipBaseProducts(null) );

            return( mapping.findForward( "receiveLotInfo" ) );
        }

        if( "receiveLotInfoXLS".equalsIgnoreCase( action ) )
        {
            String vendorNames      = request.getParameter( "prompt0" );
            String reportType       = request.getParameter("reportType");
            String processType      = transitForm.getProcessName();
            String processstepIds   = transitForm.getProcessStepId()+"";
            String baseProductIds   = transitForm.getBaseProductId()+"";
            String fromDate   = transitForm.getFromDate();
            String toDate   = transitForm.getToDate();
                        
            if ( "AsOfDate".equalsIgnoreCase(reportType) )
            {
                if (toDate == null )
                {
                    toDate = StringUtils.formatDateToString(new Date() );
                }

                fileName = "Receive Lot Report as On "+ StringUtils.formatDate(toDate, "MM/dd/yyyy", "dd-MMM-yyyy" ) +"_"+ DateUtil.getTimeStamp() ;
            }
            else
            {
                fileName = "Receive Lot Report From "+StringUtils.formatDate(fromDate, "MM/dd/yyyy", "dd-MMM-yyyy" ) + " To " +StringUtils.formatDate(toDate, "MM/dd/yyyy", "dd-MMM-yyyy" ) +"_"+ DateUtil.getTimeStamp() ;
            }
            lotInfoList = DataDumpReportsDAO.getReceivingReport ( null, processType, processstepIds, baseProductIds, vendorNames, fromDate, toDate, reportType);

            workbook =  DataDumpReportsHelper.getWorkbook(lotInfoList, "Receive Lot Report",  fromDate, toDate, null );
                        
             ExcelUtils.generateExcelReport( workbook, fileName, response );
        }

        return null;
    }

    private ArrayList<LabelValueBean> loadReceiveLotProcess()
    {
        ArrayList<LabelValueBean> processList = new ArrayList<LabelValueBean>();
        processList.add(new LabelValueBean(Constants.LOCATION_TYPE_FAB,Constants.LOCATION_TYPE_FAB));
        processList.add(new LabelValueBean(Constants.LOCATION_TYPE_SORT,Constants.LOCATION_TYPE_SORT));
        processList.add(new LabelValueBean(Constants.LOCATION_TYPE_DIE_BANK,Constants.LOCATION_TYPE_DIE_BANK));
        processList.add(new LabelValueBean(Constants.LOCATION_TYPE_ASSEMBLY,Constants.LOCATION_TYPE_ASSEMBLY));
        processList.add(new LabelValueBean(Constants.LOCATION_TYPE_FT,Constants.LOCATION_TYPE_FT));
        processList.add(new LabelValueBean(Constants.LOCATION_TYPE_FG,Constants.LOCATION_TYPE_FG));
        

        return  processList;
    }
}
